﻿using System.Linq;

using Whoever.Framework.Utils;
using Whoever.Framework.Enum;
using Whoever.Framework.CustomException;

using Whoever.Patterns.Business;
using System;

using Whoever.Health.DataAccess.Repositories;
using Whoever.Health.Business.Entities;

namespace Whoever.Health.Business
{
    public class UserManager : Manager<User>
    {
        public UserManager()
            : base(new UserRepository())
        {

        }

        public User Login(User user)
        {
            user = ResolveAccessMethod(user);
            user = AttempLogin(user);
            if (user.IsLoggedin)
            {
                Repository.Update(user);
                return user;
            }
            else
                throw new BusinessException(Localized.Message("Login", MessageType.Error));
        }

        public void Logout(User user)
        {
            user.IsLoggedin = false;
            Repository.Update(user);
        }

        protected User ResolveAccessMethod(User user)
        {
            if (user.Account.IndexOf('@') != -1)
            {
                user.Email = user.Account;
                user.Account = string.Empty;
            }
            return user;
        }

        protected User AttempLogin(User user)
        {
            var realUser = new User();

            if (!string.IsNullOrEmpty(user.Account))
                realUser = Repository.GetAll().Where(e => e.Account.ToUpper() == user.Account.ToUpper()).SingleOrDefault();

            if (!string.IsNullOrEmpty(user.Email))
                realUser = Repository.GetAll().Where(e => e.Email.ToUpper() == user.Email.ToUpper()).SingleOrDefault();

            if (realUser != null)
                //Case sensitive password
                if (Cryptography.Decrypt(realUser.Password) == user.Password)
                {
                    user = realUser;
                    user.IsLoggedin = true;
                }
                else
                    user.IsLoggedin = false;

            return user;
        }
    }
}
